package com.yt.lxh.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yt.lxh.acl.mapper.RoleMapper;
import com.yt.lxh.acl.mapper.RoleUserMapper;
import com.yt.lxh.acl.service.RoleService;
import com.yt.lxh.common.service.CheckLogin;
import com.yt.lxh.dto.role.RoleDto;
import com.yt.lxh.model.acl.Admin;
import com.yt.lxh.model.acl.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleUserMapper roleUserMapper;

    @Autowired
    private CheckLogin checkLogin;


    //角色分页列表
    @Override
    public IPage<Role> selectRolePage(Page<Role> pageParams, RoleDto roleDto) {
        //获取条件值
        String roleName = roleDto.getRoleName();
        //创建mp条件对象
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        //判断条件值是否为空，如果不为空封装查询的条件
        if (!StringUtils.isEmpty(roleName)){
            wrapper.like(Role::getRoleName,roleName);
        }
        //调用方法实现条件分页查询
        Page<Role> rolePage = baseMapper.selectPage(pageParams, wrapper);
        //返回分页对象
        return rolePage;
    }

    //添加角色
    @Override
    public void saveRole(Role role,String token) {
        Admin admin = checkLogin.checkAdminLogin();
        role.setCreateUser(admin.getUsername());
        role.setUpdateUser(admin.getUsername());
        roleMapper.insert(role);
    }

    //查询所有角色
    @Override
    public Map<String, Object> findAllRoles(Integer adminId) {
        //1 查询所有角色
        List<Role> roleList = roleMapper.selectList(Wrappers.<Role>lambdaQuery().select(Role::getRoleName,Role::getId,Role::getRoleCode));
        //2 分配过的角色列表
        //根据userId查询用户分配过角色id列表
        List<Integer> roleIds = roleUserMapper.selectRoleIdsByUserId(adminId);
        Map<String, Object> map = new HashMap<>();
        map.put("allRolesList",roleList);
        map.put("adminRoles",roleIds);
        return map;
    }
}
